// 定义分片大小，这里设置为 10MB
var CHUNK_SIZE = 10 * 1024 * 1024;

// 检查上传状态
function checkUploadStatus(file, dir) {
  return new Promise(function (resolve, reject) {
    $.ajax({
      url: "/check_upload_status",
      type: "POST",
      data: {
        filename: file.name,
        dir: $("#uploadDir").val(),
      },
      success: function (response) {
        if (response.success) {
          resolve(response.data.uploaded_chunks);
        } else {
          reject(response.message);
        }
      },
      error: function (jqXHR, textStatus, errorThrown) {
        try {
          var response = JSON.parse(jqXHR.responseText);
          if (response && response.message) {
            reject(response.message);
            return;
          }
        } catch (error) {}
        reject("上传失败: " + textStatus + " - " + errorThrown);
      },
    });
  });
}

function resetLocalForm() {
  $("#localFile").val("");
}

function resetUrlForm() {
  $("uploadUrl").val("");
  $("#realUrl").val("");
  $("#newFilename").val("");
  $("#filesize").text("");
  $("#fileInfo").hide();
}

// 显示上传对话框
$("#btn-open-upload-dialog").on("click", function () {
  var uploadDialog = $("#upload-dialog");
  uploadDialog.addClass("is-visible");
  // 重置上传弹框内的输入组件
  $("#localFileUpload").prop("checked", true);
  $("#urlUpload").prop("checked", false);
  resetLocalForm();
  resetUrlForm();
  $("#uploadDir").val(decodeURIComponent(currentPath));
  fileInfoLoadedSuccessfully = false;
  // 启用上传按钮
  $("#btn-upload-ok").prop("disabled", false);
  // // 点击遮罩层关闭对话框
  // uploadDialog.on("click", function () {
  //   uploadDialog.removeClass("is-visible");
  // });
  // 阻止对话框内点击事件冒泡到遮罩层
  $(".upload-content").on("click", function (e) {
    e.stopPropagation();
  });
});

// 存储最近 5 秒的上传数据
var uploadData = [];
var lastUploadTime = 0;
var lastUploadedSize = 0;
// 独立的时间进度计算函数
function calculateProgressInfo(uploadedBytes, totalBytes) {
  var currentTime = Date.now();
  // 添加当前数据到数组
  uploadData.push({ time: currentTime, size: uploadedBytes });
  // 过滤掉超过 5 秒的数据
  var fiveSecondsAgo = currentTime - 5000;
  while (uploadData.length > 0 && uploadData[0].time < fiveSecondsAgo) {
    uploadData.shift();
  }

  if (uploadData.length < 2) {
    // 数据不足，使用原逻辑
    var uploadTime = currentTime - (lastUploadTime || currentTime);
    var uploadSpeed = (uploadedBytes - lastUploadedSize) / (uploadTime / 1000); // 字节/秒
  } else {
    var firstData = uploadData[0];
    var timeDiff = currentTime - firstData.time;
    var sizeDiff = uploadedBytes - firstData.size;
    var uploadSpeed = sizeDiff / (timeDiff / 1000); // 字节/秒
  }

  if (lastUploadTime && currentTime - lastUploadTime < 500) {
    // 如果最近两次上传时间小于 500 毫秒，不更新进度信息
    return;
  }

  lastUploadTime = currentTime;
  lastUploadedSize = uploadedBytes;

  var remainingBytes = totalBytes - uploadedBytes;
  var remainingTime = remainingBytes / uploadSpeed;
  var remainingTimeStr = "";
  if (remainingTime > 3600) {
    remainingTimeStr = (remainingTime / 3600).toFixed(1) + " 时";
  } else if (remainingTime > 60) {
    remainingTimeStr = (remainingTime / 60).toFixed(1) + " 分";
  } else {
    remainingTimeStr = remainingTime.toFixed(1) + " 秒";
  }
  var percentage = ((uploadedBytes / totalBytes) * 100).toFixed(2) || "-";
  var uploadedSize = formatFileSize(uploadedBytes);
  var totalSize = formatFileSize(totalBytes);
  var uploadSpeedStr = formatFileSize(uploadSpeed) + "/s";
  var msg =
    "正在上传: " +
    uploadedSize +
    "/" +
    totalSize +
    "(" +
    percentage +
    "%)" +
    " " +
    uploadSpeedStr +
    "，剩余 " +
    remainingTimeStr;
  showUploadMessage(msg, "info");
}

function uploadFile() {
  return new Promise(function (resolve, reject) {
    console.log("准备上传 ...");
    var fileInput = document.getElementById("localFileUpload");
    var file = fileInput.files[0];
    if (!file) {
      showUploadMessage("没有指定文件，取消");
      reject("没有指定文件，取消");
      return;
    }

    $("#btn-upload-ok").prop("disabled", true);
    showUploadMessage("正在上传 ...", "info");
    fileInput.value = null;

    var totalChunks = Math.ceil(file.size / CHUNK_SIZE);
    var uploadedBytes = 0; // 记录已上传的字节数

    checkUploadStatus(file, currentPath)
      .then(function (existingChunks) {
        // 计算已上传分片的字节数
        existingChunks.forEach(function (chunkIndex) {
          var start = chunkIndex * CHUNK_SIZE;
          var end = Math.min(start + CHUNK_SIZE, file.size);
          uploadedBytes += end - start;
        });

        var nextChunkIndex =
          existingChunks.length > 0
            ? Math.max.apply(null, existingChunks) + 1
            : 0;
        uploadNextChunk(nextChunkIndex);
      })
      .catch(function (error) {
        showUploadMessage(error, "error");
        reject(error);
      });

    var uploadNextChunk = function (index) {
      if (index >= totalChunks) {
        // 所有分片上传完成，合并分片
        $.ajax({
          url: "/merge_chunks",
          type: "POST",
          data: {
            filename: file.name,
            totalChunks: totalChunks,
            dir: $("#uploadDir").val(),
          },
          success: function (mergeResponse) {
            if (mergeResponse.success) {
              showUploadMessage("上传文件成功!", "success");
              loadFiles(currentPath);
              resolve();
            } else {
              showUploadMessage(mergeResponse.message, "error");
              reject(mergeResponse.message);
            }
          },
          error: function (jqXHR, textStatus, errorThrown) {
            showUploadMessage(
              "合并分片失败: " +
                textStatus +
                " - " +
                errorThrown +
                "\n" +
                (jqXHR.responseJSON ? jqXHR.responseJSON.message : ""),
              "error"
            );
            reject("合并分片失败");
          },
        });
        return;
      }

      var start = index * CHUNK_SIZE;
      var end = Math.min(start + CHUNK_SIZE, file.size);
      var chunk = file.slice(start, end);
      var chunkSize = end - start;

      var formData = new FormData();
      formData.append("chunk", chunk);
      formData.append("filename", file.name);
      formData.append("chunkIndex", index);
      formData.append("totalChunks", totalChunks);
      formData.append("dir", $("#uploadDir").val());

      $.ajax({
        url: "/upload_chunk",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {
          if (response.success) {
            uploadedBytes += chunkSize;
            calculateProgressInfo(uploadedBytes, file.size);
            uploadNextChunk(index + 1);
          } else {
            showUploadMessage(response.message, "error");
            reject(response.message);
          }
        },
        error: function (jqXHR, textStatus, errorThrown) {
          var errorMessage =
            "上传分片失败: " +
            textStatus +
            " - " +
            errorThrown +
            "\n" +
            (jqXHR.responseJSON ? jqXHR.responseJSON.message : "");

          showUploadMessage(errorMessage, "error");
          reject(errorMessage);
        },
      });
    };
  });
}

// 隐藏文件信息区域
$("#fileInfo").hide();

// 标记文件信息是否加载成功
var fileInfoLoadedSuccessfully = false;

// 显示文件信息的函数
function showFileInfo(info) {
  showUploadMessage("");
  var fileInfoDiv = $("#fileInfo");
  if (info.success) {
    var data = info.data;
    $("#realUrl").val(data.real_url);
    $("#newFilename").val(data.filename);
    var fileSize = formatFileSize(data.size);
    $("#filesize").text(fileSize);
    fileInfoDiv.show();
    fileInfoLoadedSuccessfully = true;
    // 启用上传按钮
    $("#btn-upload-ok").prop("disabled", false);
  } else {
    $("#realUrl").val("");
    $("#newFilename").val("");
    $("#filesize").text("");
    fileInfoDiv.hide();
    showUploadMessage(info.message, "error");
    fileInfoLoadedSuccessfully = false;
    // 禁用上传按钮，仅当是 URL 上传类型时
    if ($("#urlUpload").is(":checked")) {
      $("#btn-upload-ok").prop("disabled", true);
    }
  }
}

let timer = null;
// 监听 URL 输入框的变化事件
$("#uploadUrl").on("input", function () {
  clearTimeout(timer);
  var url = $(this).val();
  if (!url) {
    // 如果 URL 输入框为空，清空显示区域并隐藏文件信息区域
    $("#realUrl").val("");
    $("#newFilename").val("");
    $("#filesize").text("");
    $("#fileInfo").hide();
    fileInfoLoadedSuccessfully = false;
    // 禁用上传按钮，仅当是 URL 上传类型时
    if ($("#urlUpload").is(":checked")) {
      $("#btn-upload-ok").prop("disabled", true);
    }
    return;
  }
  timer = setTimeout(function () {
    // 显示正在获取文件信息的提示
    showUploadMessage("正在获取文件信息...", "info");
    $("#btn-upload-ok").prop("disabled", true); // 禁用上传按钮
    $("#fileInfo").hide();
    fileInfoLoadedSuccessfully = false;
    // 这里先不禁用上传按钮，等待获取结果
    // 调用接口获取文件信息
    $.getJSON(
      "/get_file_info?url=" + encodeURIComponent(url.replace(/\+/g, "%2B")),
      function (response) {
        showFileInfo(response);

        $("#btn-upload-ok").removeProp("disabled");
      }
    ).fail(function (jqXHR, textStatus, errorThrown) {
      $("#btn-upload-ok").removeProp("disabled");
      var response;
      try {
        response = JSON.parse(jqXHR.responseText);
      } catch (e) {}
      if (response) {
        if (response.message) {
          showFileInfo({
            success: false,
            message: response.message,
          });
          return;
        }
      }
      var errorMessage = "获取信息失败: " + textStatus + " - " + errorThrown;
      showFileInfo({
        success: false,
        message: errorMessage,
      });
    });
  }, 500);
});

// 监听上传类型切换事件
$("#localUpload, #urlUpload").on("change", function () {
  if ($("#localUpload").is(":checked")) {
    // 本地上传，启用按钮
    $("#btn-upload-ok").prop("disabled", false);
  } else if ($("#urlUpload").is(":checked")) {
    // URL 上传，根据文件信息状态决定是否禁用按钮
    if (!fileInfoLoadedSuccessfully) {
      $("#btn-upload-ok").prop("disabled", true);
    } else {
      $("#btn-upload-ok").prop("disabled", false);
    }
  }
});

// 修改上传按钮点击事件
$("#btn-upload-ok").on("click", function () {
  $(this).prop("disabled", true); // 禁用按钮

  var uploadMethod = document.querySelector(
    'input[name="uploadMethod"]:checked'
  ).value;

  var uploadPromise;

  if (uploadMethod === "local") {
    uploadPromise = uploadFile();
  } else if (uploadMethod === "url") {
    if (!fileInfoLoadedSuccessfully) {
      showUploadMessage("信息加载失败，请检查 URL 或重新获取信息", "error");
      return;
    }

    uploadPromise = uploadUrl();
  }

  if (uploadPromise) {
    uploadPromise
      .then(function () {
        // 上传成功，关闭对话框
        setTimeout(function () {
          $("#upload-dialog").removeClass("is-visible");
        }, 1000);
      })
      .catch(function (error) {
        console.error("上传失败:", error);
        // 上传失败，不关闭对话框
        $("#btn-upload-ok").prop("disabled", false);
      });
  }
});

// 修改 uploadUrl 函数，将新文件名作为参数传递到后台
function uploadUrl() {
  return new Promise(function (resolve, reject) {
    var url = document.getElementById("uploadUrl").value;
    if (!url) {
      console.log("没有指定 URL，取消");
      reject("没有指定 URL，取消");
      return;
    }

    var newFilename = $("#newFilename").val();
    if (!newFilename) {
      console.log("没有指定新文件名，取消");
      reject("没有指定新文件名，取消");
      return;
    }

    showUploadMessage("正在上传 ...", "info");

    var dir = encodeURIComponent($("#uploadDir").val());
    url = encodeURIComponent(url.replace(/\+/g, "%2B"));
    newFilename = encodeURIComponent(newFilename);
    var api =
      "/upload_from_url?url=" +
      url +
      "&dir=" +
      dir +
      "&newFilename=" +
      newFilename;

    // 创建 EventSource 实例
    var eventSource = new EventSource(api);
    $("#btn-upload-ok").prop("disabled", true);
    eventSource.onmessage = function (event) {
      try {
        var data = JSON.parse(event.data);
        if (data.success) {
          if (data.hasOwnProperty("progress")) {
            calculateProgressInfo(data.downloadedSize, data.totalSize);
          }
          if (data.downloadedSize === data.totalSize) {
            showUploadMessage("从 URL 上传文件成功!", "success");
            loadFiles(currentPath);
            eventSource.close();
            resolve();
          }
        } else {
          showUploadMessage(data.message, "error");
          eventSource.close();
          reject(data.message);
        }
      } catch (error) {
        console.error("解析 SSE 数据出错:", error);
        showUploadMessage("解析上传结果出错，请稍后重试", "error");
        eventSource.close();
        reject("解析上传结果出错");
        $("#btn-upload-ok").removeProp("disabled");
      }
    };

    // eventSource.onerror = function (error) {
    //   console.error("SSE 连接出错:", error);
    //   showUploadMessage("从 URL 上传失败，请稍后重试", "error");
    //   eventSource.close();
    //   reject("SSE 连接出错");
    // };
  });
}

function showUploadMessage(message) {
  $("#uploadMessage").text(message);
}

$("#btn-upload-cancel").on("click", function () {
  $("#upload-dialog").removeClass("is-visible");
});

$("#localUpload").on("change", function () {
  if ($(this).is(":checked")) {
    $("#upload-local").show();
    $("#upload-url").hide();
  }
});

$("#urlUpload").on("change", function () {
  if ($(this).is(":checked")) {
    $("#upload-local").hide();
    $("#upload-url").show();
  }
});
// 默认显示本地上传
$("#upload-local").show();
$("#upload-url").hide();
